package realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import pojo.SysUser;
import service.MenuService;
import service.RoleService;
import service.UserService;

import java.util.Set;

public class MyuserRealm extends AuthorizingRealm  {

    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Override
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
         SysUser user = (SysUser)principalCollection.getPrimaryPrincipal();
         int uid = user.getId();
        Set<String> roles = roleService.findRoleByUserId(uid);

        Set<String> perms = menuService.findPermsByUserId(uid);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();


       authorizationInfo.setRoles(roles);
       authorizationInfo.setStringPermissions(perms);
        return null;
    }

    @Override
    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();

        String password = new String((char[])token.getCredentials());

        SysUser user = userService.selectOne(username);

        if(user==null){
            throw  new UnknownAccountException("账户不存在");
        }
        if(password==null && !password.equalsIgnoreCase(user.getPassword())){
            throw new IncorrectCredentialsException("输入密码错误");
        }
        if(user.getStatus()!=1){
            throw new LockedAccountException("账户已经锁定");
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user
        ,password,user.getRealname());


        return authenticationInfo;



    }














}
